package com.tsk.base.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.type.TypeHandlerRegistry;

import java.text.DateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * @author: 黄嘉振
 * @create: 2023/4/25 18:03
 * @description: 自定义 mybatis SQL拦截器，用于将执行的SQL与参数整合在一起并打印
 **/
@Slf4j
@Intercepts({
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}),
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class}),
        @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})
})
public class SQLInterceptor implements Interceptor {

    // getBoundSql 获取的SQL 参数 ？ 都会在前面带有空格，为避免与参数值带有?使用拦截错误，故在\\? 前添加空格(\\x20 表示空格)
    private static final String REGEX = "\\x20\\?";

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        if (!log.isDebugEnabled()) {
            return invocation.proceed();
        }
        //获取XML中的一个select、insert、delete、update节点，第一条SQL语句
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        Object parameter = null;
        //获取参数，if语句成立，表示SQL语句有参数，参数格式为map
        if (invocation.getArgs().length > 1) {
            parameter = invocation.getArgs()[1];
        }
        //boundsQL就是封装mybatis最终产生的SQL类
        String sql = showSql(mappedStatement.getConfiguration(), mappedStatement.getBoundSql(parameter));
        log.debug("sql : " + sql);
        Object result = invocation.proceed();
        log.debug("result : " + result.toString());
        return result;
    }

    private String showSql(Configuration configuration, BoundSql boundSql) {
        Object parameterObject = boundSql.getParameterObject();
        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
        //SQL语句中多个空格都用一个空格代替
        String sql = boundSql.getSql().replaceAll("[\\s]+", " ");
        try {
            if (parameterMappings.size() > 0 && parameterObject != null) {
                //获取类型处理器注册器，类型处理器的功能是进行Java类型和数据库类型的转换
                TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
                //如果根据parameterObject.getClass()可以找到对应的类型，则替换
                if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
                    String value = getParameterValue(parameterObject);
                    sql = sql.replaceAll(REGEX, " " + value);
                    return sql;
                }
                //metaObject 主要是封装了originalObject对象，提供了get和set的方法用于获取和设置originalObject的属性值，
                //主要支出Javabean、collectin、 map三证类型对象的操作
                MetaObject metaObject = configuration.newMetaObject(parameterObject);
                for (ParameterMapping parameterMapping : parameterMappings) {
                    String propertyName = parameterMapping.getProperty();
                    if (metaObject.hasGetter(propertyName)) {
                        Object obj = metaObject.getValue(propertyName);
                        sql = sql.replaceFirst(REGEX, " " + getParameterValue(obj));
                    } else if (boundSql.hasAdditionalParameter(propertyName)) {
                        // 动态SQL
                        Object obj = boundSql.getAdditionalParameter(propertyName);
                        sql = sql.replaceFirst(REGEX, " " + getParameterValue(obj));
                    }
                }

            }
        } catch (Exception e) {
            log.error("SQL 拦截器处理异常: " + e);
        }
        return sql;
    }

    private String getParameterValue(Object obj) {
        String value;
        if (obj instanceof String) {
            value = "'" + obj + "'";
        } else if (obj instanceof Date) {
            DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.CHINA);
            value = "'" + formatter.format(obj) + "'";
        } else {
            if (obj != null) {
                value = obj.toString();
            } else {
                value = "null";
            }
        }
        return value;
    }
}
